<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="title">陈氏族谱后台登录</h2>
      <el-form :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :loading="loading" style="width:100%">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import request from '@/api/request';
export default {
  data() {
    return {
      form: { username: '', password: '' },
      loading: false,
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    };
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (!valid) return;
        this.loading = true;
        request({
          url: '/api/v1/auth/login',
          method: 'post',
          data: this.form
        }).then(response => {
          console.log('原始响应:', response);
          return response;
        })
                          .then(data => {
          console.log('登录成功，响应数据:', data);
          
          // 验证响应数据
          if (!data || !data.accessToken) {
            console.error('响应数据无效:', data);
            throw new Error('登录响应中没有accessToken');
          }
          
          // 保存token
          this.$store.commit('setToken', data.accessToken);
          this.$store.commit('setRefreshToken', data.refreshToken);
          
          // 保存用户信息
          const userInfo = {
            userId: data.userId,
            username: data.username,
            nickname: data.nickname,
            avatar: data.avatar,
            userType: data.userType,
            clanId: data.clanId,
            branchId: data.branchId,
            memberId: data.memberId,
            authorities: data.authorities
          };
          
          // 验证用户信息
          if (!userInfo.userId || !userInfo.username) {
            throw new Error('登录响应中用户信息不完整');
          }
          
          this.$store.commit('setUserInfo', userInfo);
          
          // 解析权限
          if (data.authorities) {
            const permissions = data.authorities.split(',').filter(p => p.trim());
            this.$store.commit('setPermissions', permissions);
          }
          
          console.log('用户信息已保存，准备跳转到首页');
          console.log('保存后的状态 - accessToken:', this.$store.state.accessToken);
          console.log('保存后的状态 - userInfo:', this.$store.state.userInfo);
          console.log('保存后的状态 - permissions:', this.$store.state.permissions);
          console.log('保存后的状态 - isLoggedIn:', this.$store.getters.isLoggedIn);
          
          // 等待状态更新完成
          this.$nextTick(() => {
            console.log('nextTick后的状态 - isLoggedIn:', this.$store.getters.isLoggedIn);
            this.$router.push('/');
          });
        })
        .catch(error => {
          this.$message.error(error.message || '登录失败');
        })
        .finally(() => {
          this.loading = false;
        });
      });
    }
  }
};
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}
.login-card {
  width: 350px;
  padding: 30px 20px 20px 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}
.title {
  text-align: center;
  margin-bottom: 30px;
  color: #409EFF;
}
</style> 